﻿var oGadgetDocument = System.Gadget.document;

// --------------------------------------------------------------------
// Display the Flyout state in the gadget.
// --------------------------------------------------------------------
function showFlyout() {
    System.Gadget.Flyout.show = true;
}

// --------------------------------------------------------------------
// Hide the flyout and display the Flyout state in the gadget.
// --------------------------------------------------------------------
function hideFlyout() {
    //oGadgetDocument.getElementById("strFlyoutFeedback").innerText = "Flyout hidden.";
    System.Gadget.Flyout.show = false;
}

$().ready(function() {
    System.Gadget.settingsUI = "Settings.html";
    System.Gadget.Flyout.file = "Flyout.html";
    System.Gadget.Flyout.onShow = showFlyout;
    System.Gadget.Flyout.onHide = hideFlyout;
});

$(document).ready(function () {
    $("#upgradeLink").hide();
    startUpdateCheck();

    $("#chart_div").hide();
    $("#refreshLink").click(function (event) {
        refreshData();
        event.preventDefault();
    });

    $("#flyoutLink").click(function (event) {
        System.Gadget.Flyout.show = !System.Gadget.Flyout.show;
        event.preventDefault();
    });

    refreshData();

    System.Gadget.onSettingsClosed = function (event) {
        if (event.closeAction == event.Action.commit) {
            // settings changed. kick the refresh.
            refreshData();
            setupPolling();
        }
    };

    setupPolling();



});

function setupPolling() {
    if (pollingTimer) {
        clearInterval(pollingTimer);
    }

    var interval = System.Gadget.Settings.read("interval");
    if (interval != "") {
        pollingTimer = setInterval(refreshData, interval * 1000 * 60);
    }
}

var pollingTimer;

function refreshData() {
    $("#error_div").hide();
    $("#chart_div").hide();
    $("#loading_div").fadeIn();
    getUsageData(drawPie, errorHandler);
}

function errorHandler(message) {
    $("#loading_div").hide();
    $("#error_div").text(message);
    $("#error_div").show();
}

function drawPie(usageData) {
    var totalAvailable = 0;
    var totalUsed = 0;
    var hasCap = false;
    var hasUncapped = false;
    var uncappedIdx = -1;
    
    for (var idx in usageData) {
        if (!usageData[idx].isUncapped) {
            var packSize = parseFloat(usageData[idx].size);
            var usedPercent = parseFloat(usageData[idx].usedPercentage) / 100;
            var used = packSize * usedPercent;
            var available = packSize - used;
            hasCap = true;
            totalAvailable += available;
            totalUsed += used;
        } else {
            // there should be only one of these else it wouldn't make sense.
            hasUncapped = true;
            uncappedIdx = idx;
        }
    }

    var total = totalAvailable + totalUsed;
    var totalUsedPercent = (totalUsed / total) * 100;

    if (hasCap && !(hasUncapped && totalUsedPercent == 100)) {
        var totalAvailablePercent = (totalAvailable / total) * 100;

        $("#chart").attr("title", "Used: " + totalUsed.toFixed(2) + "GB (" + totalUsedPercent.toFixed(2) + "%) <br/> Avail: " + totalAvailable.toFixed(2) + "GB (" + totalAvailablePercent.toFixed(2) + "%) ");
        $("#chart").tooltip({ position: 'top center' });


        var data = $('#chartData');
        data.empty();
        data.append("<tr style=\"color: #133915; background-color: #5b7a5c;\"><td>Available</td><td>" + totalAvailable + "</td></tr>");
        data.append("<tr style=\"color: #b70b0b; background-color: #5b0101;\"><td>Used</td><td>" + totalUsed + "</td></tr>");
        debug('running pie');
        pieChart('chart', '#chartData');
    } else if (hasUncapped) {
        $('#chart_div').empty();
        $('#chart_div').append('<p id="uncapped">' + usageData[uncappedIdx].name + '<br/><br/>Usage:<br/>' + usageData[uncappedIdx].usage + '</p>');
    }
    $("#loading_div").hide();
    $("#chart_div").fadeIn();

}

function startUpdateCheck() {
    var oReq = getXMLHttpRequest();
    if (oReq != null) {
        oReq.open("GET", "http://afrihostgadget.codeplex.com/Project/ProjectRss.aspx?ProjectRSSFeed=codeplex://release/afrihostgadget", true);
        oReq.onreadystatechange = function () {
            if (oReq.readyState == 4 && oReq.status == 200) {
                var responseText = oReq.responseText;
                var liveGadgetDoc = $.parseXML(responseText);
                //debugger;                
                var $gadgetXml = $(liveGadgetDoc);
                var items = $gadgetXml.find('item');
                var version;
                var versionFound = false;

                for (var i = 0; i < items.length && !versionFound; i++) {
                    var title = $(items[i]).find('title');
                    var titleText = title.text();
                    if (titleText.indexOf("Released:") == 0) {
                        var endOfVersion = titleText.indexOf(' ', 26);
                        version = titleText.substring(26, endOfVersion);
                        versionFound = true;
                    }
                }

                if (versionFound) {
                    var currentVersion = System.Gadget.version;
                    var isUpgrade = compareVersions(version, currentVersion);
                    if (isUpgrade) {
                        $("#upgradeLink").show();
                    }
                }


                /*
                var currentVersion = System.Gadget.version;
                var isUpgrade = compareVersions(version, currentVersion);
                if (isUpgrade) {
                //$("#upgradeLink").show();
                }
                */
            }
        };
        oReq.send();
    }
}

function compareVersions(liveVersion, currentVersion) {
    var liveArray = createVersionArray(liveVersion);
    var currentArray = createVersionArray(currentVersion);
    for (var i = 0; i < liveArray.length; i++) {
        if (liveArray[i] > currentArray[i]) {
            return true;
        }
        else if (liveArray[i] < currentArray[i]) {
            return false;
        }
    }
    
    return false;
}

function createVersionArray(version) {
    var result = new Array();
    var parts = version.split('.');
    for (var i = 0; i < parts.length; i++) {
        result[i] = parseInt(parts[i]);
    }
    return result;
}